<?php
namespace app\admin\controller;
use app\common\controller\AdminController;
use EasyAdmin\upload\Uploadfile;
use think\db\Query;
use think\facade\Lang;


class Ajax extends AdminController{
    public function getRegion(){
        $Region=\think\facade\Db::name("region");
        $map['pid']=input("pid");
        $map['type']=input("type");
        $list=$Region->where($map)->select();
        echo json_encode($list);
    }

    /**
     * 加载语言包.
     */
    public function lang()
    {
        header('Content-Type: application/javascript');
        $controllername = request()->param('controllername');
        //默认只加载了控制器对应的语言名，你还根据控制器名来加载额外的语言包
        $this->loadlang($controllername);

        return jsonp(Lang::get(), 200, [], ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
    }

    public function initAdmin(){
        $cacheData = cache('initAdmin_' .$this->admin['admin_id']);
        if (!empty($cacheData)) {
            return json($cacheData);
        }
        $authRule = \think\facade\Db::name('auth_rule')->field('id,title,icon,href,pid,target')->where('menustatus','=','1')->order('sort')->select()->toArray();
        $data = [
            'logoInfo' => [
                'title' => '管理后台',
                'image' => $this->system['logo'],
                'href'  => myurl('index/index'),
            ],
//            homeInfo: {title: "后台首页", icon: "fa fa-home", href: "/admindemo/index/welcome.html"}
            'homeInfo' => ['title'=>"后台首页", 'icon'=>"fa fa-home",'href'=> "/admin/index/main.html"],
            'menuInfo' => $this->getMenu(0,$authRule),
        ];
        cache('initAdmin_' .$this->admin['admin_id'],$data);
        return json($data);
    }

    protected function getMenu($pid,$authRule){

        $treeList = [];
        foreach ($authRule as &$v) {
            $check = true;
            if(!empty($v['href']) && $this->admin['group_id']!=1){
                if($this->adminRules && !in_array($v['id'],$this->adminRules)){
                    $check=false;
                }
            }

            if ($pid == $v['pid'] && $check) {
                !empty($v['href']) && $v['href'] = myurl($v['href']);
                $node = $v;
                $child = $this->getMenu($v['id'],$authRule);
                if (!empty($child)) {
                    $node['child'] = $child;
                }
                //空菜单做折叠
                $treeList[] = $node;
                /*
                if (!empty($v['href']) || !empty($child)) {
                    $treeList[] = $node;
                }
                 */
            }
        }
        return $treeList;
    }


    /**
     * 上传文件
     */
    public function upload()
    {
        $this->checkPostRequest();
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = config('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            $this->success($upload['msg'],null, ['url' => $upload['url']]);
        } else {
            $this->error($upload['msg']);
        }
    }

    /**
     * 上传图片至编辑器
     * @return \think\response\Json
     */
    public function uploadEditor()
    {
        $this->checkPostRequest();
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('upload'),
        ];
        $uploadConfig = config('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            return json([
                'error'    => [
                    'message' => '上传成功',
                    'number'  => 201,
                ],
                'fileName' => '',
                'uploaded' => 1,
                'url'      => $upload['url'],
            ]);
        } else {
            $this->error($upload['msg']);
        }
    }

    /**
     * 获取上传文件列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUploadFiles()
    {
        $get = $this->request->get();
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 10;
        $title = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $this->model = new \app\admin\model\SystemUploadfile();
        $count = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->count();
        $list = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->page($page, $limit)
            ->order($this->sort)
            ->select();
        $data = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }


}
